import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  resourceNameList: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_RESOURCENAMELIST: (state, resourceNameList) => {
    state.resourceNameList = resourceNameList
  }
}
// 用户登录
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 请求登录接口
      login({ username: username.trim(), password: password }).then(response => {
        // 获取响应data数据
        const { data } = response
        // console.log('responseresponseresponseresponseresponseresponseresponseresponse::::',response);

        commit('SET_TOKEN',data.rows.token)
        // token存入Cookies
        setToken(data.rows.token)
        localStorage.setItem("loginToken", data.rows.token)
        localStorage.setItem("website",'FTP_WEBSITE');

        /* 之前的设置token接口 */
        // 设置vuex的token
        // commit('SET_TOKEN', data.token_type+' '+data.access_token)
        // // token存入Cookies
        // setToken(data.token_type+' '+data.access_token)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 请求接口
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          reject('验证失败，请从新登录！.')
        }
        // 解构获取接口返回的 roles, name, avatar, introduction 等信息
        // const { roles, name, avatar, introduction } = data
        const { name,resourceNameList } = data.rows
        console.log('获取用户信息获取用户信息',resourceNameList);
        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('获取用户信息: roles 必须是一个非空数组!')
        // }
        // 设置vuex 状态信息
        // commit('SET_ROLES', roles)
        commit('SET_ROLES', ['admin']) //测试路由文件使用
        commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)

        commit('SET_RESOURCENAMELIST', resourceNameList)

        resolve(data.rows)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {

      commit('SET_TOKEN', '')
      // 清理权限
      commit('SET_RESOURCENAMELIST', '')
      commit('SET_ROLES', [])
      localStorage.setItem("loginToken", '')
      localStorage.setItem("website",'');
      // 清除cookie中的token
      removeToken()
      // 重置路由
      resetRouter()
      // 账户切换，更新快捷标签栏按钮显示的账户信息
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()

      // logout().then(() => {
      //   // 清除token
      //   commit('SET_TOKEN', '')
      //   // 清理权限
      //   commit('SET_ROLES', [])
      //   // 清除cookie中的token
      //   removeToken()
      //   // 重置路由
      //   resetRouter()

      //   // reset visited views and cached views
      //   // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      //   // 账户切换，更新快捷标签栏按钮显示的账户信息
      //   dispatch('tagsView/delAllViews', null, { root: true })

      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })




    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_RESOURCENAMELIST', '')
      commit('SET_ROLES', [])
      localStorage.setItem("loginToken", '')
      localStorage.setItem("website",'');
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    // dys6230
    // const token = role + '-token'

    // commit('SET_TOKEN', token)
    // setToken(token)

    // const { roles } = await dispatch('getInfo')
    const  roles  = ['admin']
    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
